package com.jaryle.wenxin.util.message;

import com.jaryle.wenxin.bean.message.BaseMessage;
import com.thoughtworks.xstream.XStream;
import jdk.nashorn.internal.ir.JumpToInlinedFinally;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描述:
 * 消息处理工具，把消息转成map
 *
 * @author jaryle
 * @version V1.0
 * @create 2018-11-27
 */
public class MessageUtil {
    /**
     * 微信定义的各种消息类型
     */
    //文本
    public static final String MESSAGE_TEXT = "text";
    //图片
    public static final String MESSAGE_IMAGE = "image";
    //语音
    public static final String MESSAGE_VOICE = "voice";
    //视频
    public static final String MESSAGE_VIDEO = "video";
    //断视频
    public static final String MESSAGE_SHORTVIDEO = "shortvideo";
    //链接消息
    public static final String MESSAGE_LINK = "link";
    //地理位置
    public static final String MESSAGE_LOCATION = "location";
    //事件
    public static final String MESSAGE_EVENT = "event";
    //关注事件
    public static final String MESSAGE_SUBSCRIBE = "subscribe";
    //取消关注事件
    public static final String MESSAGE_UNSUBSCRIBE = "unsubscribe";
    //单击事件
    public static final String MESSAGE_CLICK = "CLICK";
    //跳转链接时的事件推送
    public static final String MESSAGE_VIEW = "VIEW";

    public static final String MESSAGE_SCAN = "SCAN";

    /**
     * 将接收到的XML格式，转化为Map对象
     * @param req 将request对象，通过参数传入
     * @return 返回转换后的Map对象
     */
    public static Map<String,String> xmlToMap(HttpServletRequest req) throws Exception{
        Map<String,String> map = new HashMap<String,String>();
        //从dom4j的jar包中，拿到SAXReader对象。
        SAXReader reader = new SAXReader();
        InputStream in =null;
        try{
            //从request中，获取输入流
            in = req.getInputStream();
            //从reader对象中,读取输入流
            Document doc =  reader.read(in);
            //获取XML文档的根元素
            Element root = doc.getRootElement();
            //获得根元素下的所有子节点
            List<Element> list = root.elements();
            //遍历list对象，并将结果保存到集合中
            for (Element e : list) {
                map.put(e.getName(), e.getText());
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                in.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return map;
    }
}
